# -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import User
from django.db.utils import IntegrityError
from django.views.decorators.csrf import csrf_exempt
import time
from apps.users.forms.edit import *
from core.decorators import render
from core.enum import REQUEST_POST
import Image

@csrf_exempt
@render('users/edit.html')
def action(request):

    FORM_PASSWORD = "password"
    FORM_AVATAR = "avatar"
    FORM_PROFILE = "profile"

    form_password = EditPasswordForm(initial={
        'current_password': '',
        'password': '',
        'repeat_password': ''
    })
    form_avatar = EditAvatarForm(initial={
        'avatar': ''
    })
    form_profile = EditProfileForm(initial={
        'first_name': request.user.first_name,
        'last_name': request.user.last_name,
        'username': request.user.username
    })

    if request.method == REQUEST_POST:

        if request.POST.get("form") == FORM_PASSWORD:
            form_password = EditPasswordForm(request.POST)
            if form_password.is_valid():
                if not request.user.check_password(form_password.cleaned_data.get('current_password')):
                    messages.error(request, "Неправильный текущий пароль")
                else:
                    request.user.set_password(form_password.cleaned_data.get('password'))
                    request.user.save()
                    messages.success(request, "Ваш пароль был успешно изменен")
                    form_password = EditPasswordForm(initial={
                        'current_password': '',
                        'password': '',
                        'repeat_password': ''
                    })

        elif request.POST.get("form") == FORM_AVATAR:
            form_avatar = EditAvatarForm(request.POST, request.FILES)
            if form_avatar.is_valid():
                file = request.FILES['avatar']
                image = Image.open(file)
                image = image.resize((36, 36), Image.ANTIALIAS)

                file_name = "%s" % (
                    request.user.username
                )

                image.save(
                    "%s/uploads/avatars/%s.jpg" % (
                        settings.ROOT,
                        file_name
                    ), "JPEG"
                )
                request.user.get_profile().avatar = "%s.jpg" % file_name
                request.user.get_profile().save()
                messages.success(request, "Ваш аватар был успешно обновлен")

        elif request.POST.get("form") == FORM_PROFILE:
            form_profile = EditProfileForm(request.POST)
            if form_profile.is_valid():
                try:

                    if User.objects.filter(username = form_profile.cleaned_data.get("username")).count():
                        raise Exception()

                    request.user.first_name = form_profile.cleaned_data.get('first_name')
                    request.user.last_name = form_profile.cleaned_data.get('last_name')
                    request.user.username = form_profile.cleaned_data.get("username")
                    request.user.save()
                    messages.success(request, "Ваш профиль был успешно обновлен")

                except Exception, e:
                    messages.error(request, "Пользователь с таким ником уже зарегистрирован. Попробуйте другой.")

                form_profile = EditProfileForm(initial={
                    'first_name': request.user.first_name,
                    'last_name': request.user.last_name,
                    'username': request.user.username
                })


    return {
        'form_password': form_password,
        'form_avatar': form_avatar,
        'form_profile': form_profile
    }